package com.joint.base.activiti.listener;

import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.joint.base.entity.Duty;
import com.joint.base.entity.ProcessConfig;
import com.joint.base.exception.users.UserNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DutyService;
import com.joint.base.service.PowerService;
import com.joint.base.service.ProcessConfigService;
import com.joint.base.service.UsersService;
import com.joint.base.util.StringUtils;
import org.activiti.engine.EngineServices;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by hpj on 2015/1/16.
 */
@Component
@Transactional
public class TaskEventListener implements ActivitiEventListener {


    @Resource
    private ProcessConfigService processConfigService;
    @Resource
    private UsersService usersService;
    @Resource
    private PowerService powerService;
    @Resource
    private DutyService dutyService;


    @Override
    public void onEvent(ActivitiEvent event) {
        ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event;
        Object entity = entityEvent.getEntity();

        if(entity instanceof TaskEntity){
            TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();
            LogUtil.info(taskEntity.getAssignee());
            EngineServices engineServices = entityEvent.getEngineServices();
            HistoryService historyService = engineServices.getHistoryService();
            RuntimeService runtimeService = engineServices.getRuntimeService();
            ManagementService managementService = engineServices.getManagementService();

            //获取上一步操作人
            List<HistoricTaskInstance> hisTaskList = historyService.createHistoricTaskInstanceQuery().processInstanceId(taskEntity.getProcessInstanceId()).finished().orderByTaskCreateTime().desc().list();

            ProcessConfig processConfig = processConfigService.findConfigByActivityId(taskEntity.getProcessDefinitionId(),taskEntity.getTaskDefinitionKey());

            if(processConfig==null){
                throw new PcfgNotExistException(null);
            }

            Duty hisDuty;
            List<String> idList = Lists.newArrayList();
            if(hisTaskList.size()>0){
                HistoricTaskInstanceEntity hisTask = (HistoricTaskInstanceEntity) hisTaskList.get(0);
                List<HistoricVariableInstance> histance = historyService.createHistoricVariableInstanceQuery().taskId(hisTask.getId()).variableName("curDutyId").list();
                if(histance.size()>0){
                    HistoricVariableInstanceEntity hisVarEntity = (HistoricVariableInstanceEntity) histance.get(0);
                    String id = hisVarEntity.getTextValue();
                    hisDuty = dutyService.get(id);
                    idList.addAll(processConfigService.findSpecailByUser(processConfig, hisDuty));
                }
            }
            List<Duty> dutyList = processConfigService.findDutyByConfig(processConfig);
            for(Duty duty :dutyList){
                idList.add(duty.getUsers().getId());
            }
            if(idList.size()==0 && StringUtils.isEmpty(taskEntity.getAssignee())){
                throw new UserNotExistsException();
            }
            taskEntity.addCandidateUsers(idList);
        }
    }

    @Override
    public boolean isFailOnException() {
        //这里返回的是false，会忽略异常。 当返回true时，异常不会忽略，继续向上传播
        return false;
    }
}
